﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LIU.Tangtu.Web.App_Code
{
    /// <summary>
    /// 添加审计日志中间件
    /// </summary>
    public class AuditMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<AuditMiddleware> logger;

        /// <summary>
        /// 管道执行到该中间件时候下一个中间件的RequestDelegate请求委托，如果有其它参数，也同样通过注入的方式获得
        /// </summary>
        /// <param name="next"></param>
        public AuditMiddleware(RequestDelegate next, ILogger<AuditMiddleware> logger)
        {
            //通过注入方式获得对象
            _next = next;
            this.logger = logger;
        }

        /// <summary>
        /// 自定义中间件要执行的逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            string temp = "未匹配到路由";
            if (context.GetEndpoint() != null && (context.GetEndpoint() as RouteEndpoint) != null)
                temp = (context.GetEndpoint() as RouteEndpoint).RoutePattern.RawText;
            logger.LogInformation($"【{DateTime.Now:g}】请求地址:{context.Request.Path}\r\n请求参数:{context.Request.QueryString}\r\n匹配路由:{temp}");

            await _next(context);//把context传进去执行下一个中间件


            //await context.Response.WriteAsync("111");//响应出去时逻辑，为了验证顺序性，输出一句话
        }
    }
}
